package com.centaline.androidsalesblog.fragments.entrust;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.entrust.EditReservationActivity;
import com.centaline.androidsalesblog.activities.sale.EsfEstateDetailActivity;
import com.centaline.androidsalesblog.activities.sale.RentDetailActivity;
import com.centaline.androidsalesblog.activities.sale.RentListActivity;
import com.centaline.androidsalesblog.activities.sale.SaleDetailActivity;
import com.centaline.androidsalesblog.activities.sale.SaleListActivity;
import com.centaline.androidsalesblog.adapter.ReservationEditAdapter;
import com.centaline.androidsalesblog.api.usercenter.DeleteReservationApi;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.events.ReserveUpdate;
import com.centaline.androidsalesblog.iml.ReserveItemClick;
import com.centaline.androidsalesblog.model.businissobject.ReservationParentBo;
import com.centaline.androidsalesblog.model.databaseobject.PostDo;
import com.centaline.androidsalesblog.model.responseobject.ReservationUserCenterRo;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager;
import com.jakewharton.rxbinding.view.RxView;
import com.trello.rxlifecycle.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import rx.functions.Action1;

/**
 * 未约看
 * Created by guilin on 16/4/23.
 */
public class ReservationEditFragment extends BaseReservationFragment {

    private RelativeLayout rl_list;
    private LinearLayout ll_no_list, ll_choose_all;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private ImageView img_order_all;
    private Button btn_edit, btn_sale, btn_rent;

    private RecyclerViewExpandableItemManager expMgr;
    private ReservationEditAdapter reservationEditAdapter;

    private StringBuilder cestCodeSet = new StringBuilder();
    private StringBuilder postIds = new StringBuilder();
    private ArrayList<Integer> reserveIdList = new ArrayList<>();//约看模式
    private ArrayList<Integer> reserveIdEditModeList = new ArrayList<>();//编辑模式

    private boolean chooseAll = false;

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_reservation_edit;
    }

    @Override
    protected void findViews(View view) {
        rl_list = (RelativeLayout) view.findViewById(R.id.rl_list);
        ll_no_list = (LinearLayout) view.findViewById(R.id.ll_no_list);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        ll_choose_all = (LinearLayout) view.findViewById(R.id.ll_choose_all);
        img_order_all = (ImageView) view.findViewById(R.id.img_order_all);
        btn_edit = (Button) view.findViewById(R.id.btn_edit);
        btn_sale = (Button) view.findViewById(R.id.btn_sale);
        btn_rent = (Button) view.findViewById(R.id.btn_rent);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setHasOptionsMenu(true);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestReservationList();
            }
        });
        btn_edit.setText("预约看房");
        ll_choose_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (ReservationParentBo reservationParentBo : reservationParentBoArrayList) {
                    reservationParentBo.setCheck(!chooseAll);
                    reservationParentBo.notifyCheckList(!chooseAll);
                }
                reservationEditAdapter.notifyDataSetChanged();
                notifyData();
            }
        });

        expMgr = new RecyclerViewExpandableItemManager(null);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setHasFixedSize(false);
        reservationEditAdapter = new ReservationEditAdapter(getContext(), GlideLoad.init(this),
                reservationParentBoArrayList,
                new ReserveItemClick() {
                    @Override
                    public void itemClick(int groupPosition, int childPosition) {
                        if (childPosition < 0) {//小区
                            startActivity(new Intent(getActivity(), EsfEstateDetailActivity.class)
                                    .putExtra(ExtraConstant.CestCode, reservationParentBoArrayList.get(groupPosition).getEstateCode()));
                        } else {
                            if (reservationParentBoArrayList.get(groupPosition)
                                    .getPostDoArrayList().get(childPosition).isOnline()) {
                                if ("s".equalsIgnoreCase(reservationParentBoArrayList.get(groupPosition)
                                        .getPostDoArrayList().get(childPosition).getPostType())) {
                                    //二手房
                                    startActivity(new Intent(getActivity(), SaleDetailActivity.class)
                                            .putExtra(ExtraConstant.PostId, reservationParentBoArrayList.get(groupPosition)
                                                    .getPostDoArrayList().get(childPosition).getPostId()));
                                } else {
                                    //租房
                                    startActivity(new Intent(getActivity(), RentDetailActivity.class)
                                            .putExtra(ExtraConstant.PostId, reservationParentBoArrayList.get(groupPosition)
                                                    .getPostDoArrayList().get(childPosition).getPostId()));
                                }
                            }
                        }
                    }

                    @Override
                    public void check(boolean isChecked, int groupPosition, int childPosition) {
                        if (childPosition < 0) {
                            //父级
                            reservationParentBoArrayList.get(groupPosition).setCheck(isChecked);
                            reservationParentBoArrayList.get(groupPosition).notifyCheckList(isChecked);
                            expMgr.notifyGroupItemChanged(groupPosition);
                            expMgr.notifyChildrenOfGroupItemChanged(groupPosition);
                        } else {
                            //子级
                            reservationParentBoArrayList.get(groupPosition).getCheckList().remove(childPosition);
                            reservationParentBoArrayList.get(groupPosition).getCheckList().add(childPosition, isChecked);
                            boolean parentIsChecked = false;
                            int size = reservationParentBoArrayList.get(groupPosition).getCheckList().size();
                            for (int i = 0; i < size; i++) {
                                parentIsChecked = reservationParentBoArrayList.get(groupPosition).getCheckList().get(i);
                                if (!parentIsChecked) {
                                    break;
                                }
                            }
                            reservationParentBoArrayList.get(groupPosition).setCheck(parentIsChecked);
                            expMgr.notifyChildItemChanged(groupPosition, childPosition);
                            expMgr.notifyGroupItemChanged(groupPosition);
                        }

                        notifyData();
                    }
                });
        recyclerView.setAdapter(expMgr.createWrappedAdapter(reservationEditAdapter));
        expMgr.attachRecyclerView(recyclerView);

        RxView.clicks(btn_edit)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (reservationEditAdapter.getMode() == 0) {
                            if (postIds.toString().endsWith(",")) {
                                postIds.deleteCharAt(postIds.length() - 1);
                            }
                            if (cestCodeSet.toString().endsWith(",")) {
                                cestCodeSet.deleteCharAt(cestCodeSet.length() - 1);
                            }
                            startActivity(new Intent(getActivity(), EditReservationActivity.class)
                                    .putExtra(ExtraConstant.CestCodes, cestCodeSet.toString())
                                    .putExtra(ExtraConstant.PostId, postIds.toString())
                                    .putIntegerArrayListExtra(ExtraConstant.ReserveIDList, reserveIdList));
                        } else {
                            DeleteReservationApi deleteReservationApi = new DeleteReservationApi(ReservationEditFragment.class
                                    , ReservationUserCenterRo.class, new IResponseListener<ReservationUserCenterRo>() {
                                @Override
                                public void onResponse(ReservationUserCenterRo reservationUserCenterRo) {
                                    if (0 == reservationUserCenterRo.getResultNo()) {
                                        requestReservationList();
                                    } else {
                                        toast(reservationUserCenterRo.getMessage());
                                    }
                                }

                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    netWorkUnable();
                                }
                            });
                            deleteReservationApi.setReserveIDList(reserveIdEditModeList);
                            deleteReservationApi.startRequest();
                        }
                    }
                });

        RxView.clicks(btn_sale)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivity(new Intent(getActivity(), SaleListActivity.class));
                    }
                });

        RxView.clicks(btn_rent)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivity(new Intent(getActivity(), RentListActivity.class));
                    }
                });
    }

    private void notifyData() {
        cestCodeSet.setLength(0);//小区code
        postIds.setLength(0);//房源code
        reserveIdList.clear();//约看id
        reserveIdEditModeList.clear();//删除模式的约看id

        int size = 0;//约看数量
        for (ReservationParentBo reservationParentBo : reservationParentBoArrayList) {
            int checkListSize = reservationParentBo.getCheckList().size();
            if (reservationParentBo.getStatus() == 0) {
                size += checkListSize;
            }
            for (int i = 0; i < checkListSize; i++) {
                if (reservationParentBo.getCheckList().get(i)) {
                    if (reservationParentBo.getStatus() == 0) {
                        if (!cestCodeSet.toString().contains(reservationParentBo.getEstateCode())) {
                            cestCodeSet.append(reservationParentBo.getEstateCode()).append(",");
                        }
                        postIds.append(reservationParentBo.getPostDoArrayList().get(i).getPostId())
                                .append(",");
                        reserveIdList.add(
                                reservationBoArrayList.get(
                                        postIdArrayList.indexOf(
                                                reservationParentBo.getPostDoArrayList().get(i).getPostId())).getReserveID());
                    }
                    reserveIdEditModeList.add(
                            reservationBoArrayList.get(
                                    postIdArrayList.indexOf(
                                            reservationParentBo.getPostDoArrayList().get(i).getPostId())).getReserveID());
                }
            }
        }
        chooseAll = false;
        img_order_all.setImageResource(R.drawable.order_btn_nor);
        if (reservationEditAdapter.getMode() == 0) {
            if (reserveIdList.size() > 0) {
                btn_edit.setEnabled(true);
                btn_edit.setText(String.format(Locale.CHINA, "预约看房(%d)", reserveIdList.size()));
                if (size == reserveIdList.size()) {
                    img_order_all.setImageResource(R.drawable.order_btn_sel);
                    chooseAll = true;
                }
            } else {
                btn_edit.setEnabled(false);
                btn_edit.setText("预约看房");
            }
        } else {
            if (reserveIdEditModeList.size() > 0) {
                btn_edit.setEnabled(true);
                btn_edit.setText(String.format(Locale.CHINA, "删除(%d)", reserveIdEditModeList.size()));
                if (reservationBoArrayList.size() == reserveIdEditModeList.size()) {
                    img_order_all.setImageResource(R.drawable.order_btn_sel);
                    chooseAll = true;
                }
            } else {
                btn_edit.setEnabled(false);
                btn_edit.setText("删除");
            }
        }

    }

    @Override
    protected void requestReservationList() {
        btn_edit.setEnabled(false);
        btn_edit.setText("预约看房");
        chooseAll = false;
        img_order_all.setImageResource(R.drawable.order_btn_nor);
        if (reservationParentBoArrayList.size() > 0) {
            int count = reservationParentBoArrayList.size();
            reservationParentBoArrayList.clear();
            expMgr.notifyGroupItemRangeRemoved(0, count);
        }
        super.requestReservationList();
    }

    @Override
    protected void loadData() {
        if (!isRequest) {
            isRequest = true;
            swipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(true);
                    requestReservationList();
                }
            });
        }
    }

    @Subscribe
    public void onEventMainThread(ReserveUpdate reserveUpdate) {
        if (reserveUpdate.getStatus() == 0 ||
                reserveUpdate.getStatus() == -1) {
            swipeRefreshLayout.setRefreshing(true);
            requestReservationList();
        }
    }

    @Override
    protected boolean isReserve() {
        return false;
    }

    @Override
    protected void responsePostList(ArrayList<PostDo> temp) {
        //对房源进行排序
        ArrayList<PostDo> postDos = new ArrayList<>();
        for (String postId : postIdArrayList) {
            for (PostDo postDo : temp) {
                if (postId.equalsIgnoreCase(postDo.getPostId())) {
                    postDos.add(postDo);
                }
            }
        }

        ArrayList<String> cestCodes = new ArrayList<>();
        for (PostDo postDo : postDos) {
            if (postDo.isOnline()) {//在线
                if (cestCodes.contains(postDo.getCestCode())) {//已存在
                    reservationParentBoArrayList.get(cestCodes.indexOf(postDo.getCestCode())).add(postDo);
                    reservationParentBoArrayList.get(cestCodes.indexOf(postDo.getCestCode())).addCheck(false);
                } else {
                    int offIndex = cestCodes.indexOf("OFF_LINE");//下架房源位置
                    ReservationParentBo reservationParentBo = new ReservationParentBo(0,
                            postDo.getCestCode(),
                            postDo.getCnEstate());
                    reservationParentBo.add(postDo);
                    reservationParentBo.addCheck(false);
                    if (offIndex > -1) {
                        cestCodes.add(offIndex, postDo.getCestCode());
                        reservationParentBoArrayList.add(offIndex, reservationParentBo);
                    } else {
                        cestCodes.add(postDo.getCestCode());
                        reservationParentBoArrayList.add(reservationParentBo);
                    }

                }
            } else {//下架
                if (cestCodes.contains("OFF_LINE")) {
                    reservationParentBoArrayList.get(cestCodes.indexOf("OFF_LINE")).add(postDo);
                    reservationParentBoArrayList.get(cestCodes.indexOf("OFF_LINE")).addCheck(false);
                } else {
                    cestCodes.add("OFF_LINE");
                    ReservationParentBo reservationParentBo = new ReservationParentBo(1, "OFF_LINE", "OFF_LINE");
                    reservationParentBo.add(postDo);
                    reservationParentBo.addCheck(false);
                    reservationParentBoArrayList.add(reservationParentBo);
                }
            }
        }
        swipeRefreshLayout.setRefreshing(false);
        expMgr.notifyGroupItemRangeInserted(0, reservationParentBoArrayList.size());
        expMgr.expandAll();
        getActivity().invalidateOptionsMenu();
        refreshUi();
    }

    @Override
    protected void responseError() {
        super.responseError();
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void noData() {
        swipeRefreshLayout.setRefreshing(false);
        refreshUi();
    }

    private void refreshUi() {
        int size = reservationParentBoArrayList.size();
        rl_list.setVisibility(size == 0 ? View.GONE : View.VISIBLE);
        ll_no_list.setVisibility(size > 0 ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_reserve_list, menu);
        MenuItem edit = menu.findItem(R.id.action_edit);
        edit.setVisible(reservationParentBoArrayList.size() > 0);
        edit.setTitle(reservationEditAdapter.getMode() == 0 ? "编辑" : "完成");
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (R.id.action_edit == item.getItemId()) {
            reservationEditAdapter.setMode(reservationEditAdapter.getMode() == 0 ? 1 : 0);
            getActivity().invalidateOptionsMenu();
            if (reservationEditAdapter.getMode() == 0) {
                btn_edit.setText("预约看房");
                btn_edit.setEnabled(false);
            } else {
                btn_edit.setText("删除");
                btn_edit.setEnabled(false);
            }
            img_order_all.setImageResource(R.drawable.order_btn_nor);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
